//
//  BasicViewController.m
//  Example
//
//  Created by Jonathan Tribouharet.
//

#import "BasicViewController.h"


@interface BasicViewController (){
    NSDate *_todayDate;
    NSDate *_minDate;
    NSDate *_maxDate;
    
    NSDate *_dateSelected;
}

@property(nonatomic,weak) IBOutlet UILabel *labelShebei;
@property(nonatomic,weak) IBOutlet UILabel *labelShijian;
@property(nonatomic,weak) IBOutlet UILabel *labelLeiji;
@property(nonatomic,weak) IBOutlet UILabel *labelWancheng;
@property(nonatomic,weak) IBOutlet UILabel *labelRiqi;
@property(nonatomic,weak) IBOutlet UILabel *labelXiaohao;
@property(nonatomic,weak) IBOutlet UILabel *labelMoshi;

@property(nonatomic,weak) IBOutlet UIButton *startButton;


@property(nonatomic,assign) NSInteger aMaxID;
@property(nonatomic,strong) NSDictionary *aUserData;
@property(nonatomic,strong) NSDictionary *resultData;

-(IBAction)startPressed:(id)sender;

@end

@implementation BasicViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if(!self){
        return nil;
    }
    
    self.title = @"Basic";
    
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(APPALL.currPeripheral){
        self.labelShebei.text = APPALL.currPeripheral.name;
        self.startButton.hidden = NO;
    }else{
        self.labelShebei.text = @"无设备连接";
        self.startButton.hidden = YES;
    }
    if(APPALL.myUserItem.username){
        [self getMaxID];
    }
//    [self loadJindu];
}

-(void)getMaxID{
    //APIMaxID
    [SVProgressHUD showWithStatus:@"loading..."];
    [APPALL.netSession GET:[NSString stringWithFormat:@"%@%@",APIURL,APIMaxID]
                parameters:nil
                  progress:nil
                   success:^(NSURLSessionDataTask * task, id responseObject){
                       NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                       NSLog(@"JSON: %@", JSON);
                       if([JSON[@"get_max_no"] isEqualToString:@"success"]){
                           self.aMaxID = [JSON[@"result"] integerValue];
                           [self getIDInfo];
                       }else{
                           [SVProgressHUD dismiss];
                           //[SVProgressHUD showErrorWithStatus:@"获取进度失败"];
                       }
                   }
                   failure:^(NSURLSessionDataTask * task, NSError * error){
                       [SVProgressHUD dismiss];
                       //[SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"请求失败:%@", error.description]];
                   }];
}

-(void)getIDInfo{
    [APPALL.netSession GET:[NSString stringWithFormat:@"%@%@?start=0&end=3",APIURL,APIIDInfo]
                parameters:nil
                  progress:nil
                   success:^(NSURLSessionDataTask * task, id responseObject){
                       NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                       NSLog(@"JSON: %@", JSON);
                       if([JSON[@"get_data"] isEqualToString:@"success"]){
                           self.aUserData = JSON[@"result"];
                           [self loadJindu];
                       }else{
                           [SVProgressHUD dismiss];
                           //[SVProgressHUD showErrorWithStatus:@"获取进度失败"];
                       }
                   }
                   failure:^(NSURLSessionDataTask * task, NSError * error){
                       NSLog(@"%@",error);
                       [SVProgressHUD dismiss];
//                       [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"请求失败:%@", error.description]];
                   }];
}

-(void)loadJindu{
    [APPALL.netSession GET:[NSString stringWithFormat:@"%@%@",APIURL,APISchedule]
                parameters:nil
                  progress:nil
                   success:^(NSURLSessionDataTask * task, id responseObject){
                       NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                       NSLog(@"JSON: %@", JSON);
                       if(JSON.allKeys.count){
                           [SVProgressHUD dismiss];
                           self.resultData = JSON;
                       }else{
                           [SVProgressHUD dismiss];
                           //[SVProgressHUD showErrorWithStatus:@"获取进度失败"];
                       }
                   }
                   failure:^(NSURLSessionDataTask * task, NSError * error){
                       [SVProgressHUD dismiss];
                       //[SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"请求失败:%@", error.description]];
                   }];
    [self loadDataFromDate:[NSDate date]];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _calendarManager = [JTCalendarManager new];
    _calendarManager.delegate = self;
    _calendarManager.settings.weekDayFormat = JTCalendarWeekDayFormatSingle;
    _calendarManager.dateHelper.calendar.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];
    
    // Create a min and max date for limit the calendar, optional
    [self createMinAndMaxDate];
    
    [_calendarManager setMenuView:_calendarMenuView];
    [_calendarManager setContentView:_calendarContentView];
    [_calendarManager setDate:_todayDate];
}

#pragma mark - Buttons callback

- (IBAction)didGoTodayTouch
{
    [_calendarManager setDate:_todayDate];
}

- (IBAction)didChangeModeTouch
{
    _calendarManager.settings.weekModeEnabled = !_calendarManager.settings.weekModeEnabled;
    [_calendarManager reload];
    
    CGFloat newHeight = 300;
    if(_calendarManager.settings.weekModeEnabled){
        newHeight = 85.;
    }
    
    self.calendarContentViewHeight.constant = newHeight;
    [self.view layoutIfNeeded];
}

#pragma mark - CalendarManager delegate

// Exemple of implementation of prepareDayView method
// Used to customize the appearance of dayView
- (void)calendar:(JTCalendarManager *)calendar prepareDayView:(JTCalendarDayView *)dayView
{
    
    // Other month
    if([dayView isFromAnotherMonth]){
        dayView.hidden = YES;
    }
    // Today
    else if([_calendarManager.dateHelper date:[NSDate date] isTheSameDayThan:dayView.date]){
        dayView.circleView.hidden = NO;
        dayView.circleView.backgroundColor = TitleGreen;
        dayView.dotView.backgroundColor = [UIColor whiteColor];
        dayView.textLabel.textColor = [UIColor whiteColor];
    }
    // Selected date
    else if(_dateSelected && [_calendarManager.dateHelper date:_dateSelected isTheSameDayThan:dayView.date]){
        dayView.circleView.hidden = NO;
        dayView.circleView.backgroundColor = [UIColor moneyGreenColor];
        dayView.dotView.backgroundColor = [UIColor whiteColor];
        dayView.textLabel.textColor = [UIColor whiteColor];
    }
    // Other month
    else if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
        dayView.circleView.hidden = YES;
        dayView.dotView.backgroundColor = [UIColor redColor];
        dayView.textLabel.textColor = [UIColor lightGrayColor];
    }
    // Another day of the current month
    else{
        dayView.circleView.hidden = YES;
        dayView.dotView.backgroundColor = [UIColor redColor];
        dayView.textLabel.textColor = [UIColor blackColor];
    }
    
    if([self haveEventForDay:dayView.date] >= 0){
        dayView.dotView.hidden = NO;
    }
    else{
        dayView.dotView.hidden = YES;
    }
}

- (void)calendar:(JTCalendarManager *)calendar didTouchDayView:(JTCalendarDayView *)dayView
{
    _dateSelected = dayView.date;
    NSLog(@"...");
    [_calendarManager reload];
    // Don't change page in week mode because block the selection of days in first and last weeks of the month
    if(_calendarManager.settings.weekModeEnabled){
        return;
    }
    // Load the previous or next page if touch a day from another month
    
    if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
        if([_calendarContentView.date compare:dayView.date] == NSOrderedAscending){
            [_calendarContentView loadNextPageWithAnimation];
        }
        else{
            [_calendarContentView loadPreviousPageWithAnimation];
        }
    }
    [self loadDataFromDate:dayView.date];
}

-(void)loadDataFromDate:(NSDate*)aDate{
    static NSDateFormatter *dateFormatter2;
    if(!dateFormatter2){
        dateFormatter2 = [NSDateFormatter new];
        dateFormatter2.dateFormat = @"yyyy-MM-dd";
        
        dateFormatter2.locale = _calendarManager.dateHelper.calendar.locale;
        dateFormatter2.timeZone = _calendarManager.dateHelper.calendar.timeZone;
    }
    self.labelRiqi.text = [dateFormatter2 stringFromDate:aDate];
    int dayFlag = [self haveEventForDay:aDate];
    if(dayFlag >= 0){
        self.labelXiaohao.text = @"";
        NSString *dayData = self.aUserData[[NSString stringWithFormat:@"%d",dayFlag]];
        dayData = [dayData stringByReplacingOccurrencesOfString:@" " withString:@""];
        dayData = [dayData stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%i:",dayFlag] withString:@""];
        NSArray *dataArray = [dayData componentsSeparatedByString:@"\n"];
        NSLog(@"%@",dataArray);
        NSMutableString *mosStr = [NSMutableString string];
        for(int j = 0;j < dataArray.count - 1;j++){
            NSString *cacheS = dataArray[j];
            NSArray *cacheArr = [cacheS componentsSeparatedByString:@","];
            self.labelXiaohao.text = cacheArr[0];
            NSString *moshiS = [cacheArr[1] substringFromIndex:[cacheArr[1] length] - 2];
            NSArray *timeArr = [cacheArr[2] componentsSeparatedByString:@"/"];
            NSString *timeS = [NSString stringWithFormat:@"%@月%@日%@时%@分",timeArr[0],timeArr[1],timeArr[2],timeArr[3]];
            NSString *qiangS = [cacheArr[3] substringFromIndex:[cacheArr[3] length] - 2];
            [mosStr appendFormat:@"    模式%@强度%@，持续%@",moshiS,qiangS,timeS];
        }
        self.labelMoshi.text = mosStr;
//        self.labelMoshi.text = [NSString stringWithFormat:@"    模式%@强度%@，持续%@分钟",self.resultData[@"mode"],self.resultData[@"strength"],self.resultData[@"time"]];
    }
    else{
        self.labelXiaohao.text = @"";
        self.labelMoshi.text = @"";
    }
}

#pragma mark - CalendarManager delegate - Page mangement

// Used to limit the date for the calendar, optional
- (BOOL)calendar:(JTCalendarManager *)calendar canDisplayPageWithDate:(NSDate *)date
{
    return [_calendarManager.dateHelper date:date isEqualOrAfter:_minDate andEqualOrBefore:_maxDate];
}

- (void)calendarDidLoadNextPage:(JTCalendarManager *)calendar
{
    //    NSLog(@"Next page loaded");
}

- (void)calendarDidLoadPreviousPage:(JTCalendarManager *)calendar
{
    //    NSLog(@"Previous page loaded");
}

#pragma mark - Fake data

- (void)createMinAndMaxDate
{
    _todayDate = [NSDate date];
    
    // Min date will be 2 month before today
    _minDate = [_calendarManager.dateHelper addToDate:_todayDate months:-200];
    
    // Max date will be 2 month after today
    _maxDate = [_calendarManager.dateHelper addToDate:_todayDate months:200];
}

// Used only to have a key for _eventsByDate
- (NSDateFormatter *)dateFormatter1
{
    static NSDateFormatter *dateFormatter1;
    if(!dateFormatter1){
        dateFormatter1 = [NSDateFormatter new];
        dateFormatter1.dateFormat = @"yyyy/M/d";
    }
    
    return dateFormatter1;
}

- (void)calendar:(JTCalendarManager *)calendar prepareMenuItemView:(UILabel *)menuItemView date:(NSDate *)date
{
    static NSDateFormatter *dateFormatter3;
    if(!dateFormatter3){
        dateFormatter3 = [NSDateFormatter new];
        dateFormatter3.dateFormat = @"MMMM yyyy";
        
        dateFormatter3.locale = _calendarManager.dateHelper.calendar.locale;
        dateFormatter3.timeZone = _calendarManager.dateHelper.calendar.timeZone;
    }
    
    menuItemView.text = [dateFormatter3 stringFromDate:date];
}

- (int)haveEventForDay:(NSDate *)date{
    NSString *key = [[self dateFormatter1] stringFromDate:date];
    for(int i =0; i < self.aMaxID; i++){
        if([self.aUserData[[NSString stringWithFormat:@"%d",i]] hasPrefix:[NSString stringWithFormat:@"%i:%@",i,key]])
            return i;
    }
    return -1;
}

-(IBAction)startPressed:(id)sender{
    
}

@end
